package com.paul.sys.tools.dbutil;

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.log4j.Logger;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class HttpProxy
{
	
	private static HttpProxy instance = new HttpProxy();
	
	public static HttpProxy getInstance(){
		if(instance == null)  instance = new HttpProxy();
		return instance;
	}
	
	 private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

	    private static HttpClient client = new HttpClient(connectionManager);

	    private static MultiThreadedHttpConnectionManager[] connectionManagers = null;

	    private static HttpClient[] clients = null;

	    private static final Logger log = Logger.getLogger(HttpProxy.class);

	    private int size = 60;

	    private int maxThreadsTotal = 1000;
	    private int maxThreadsPerHost = 100;
	    private int soTimeout = 10000;
	    private int connectionTimeout = 10000;


	    @PostConstruct
	    protected void configureClient() {
	        try {
	        	maxThreadsTotal = 1000;
	            maxThreadsPerHost = 100;
	            soTimeout = 10000;
	            connectionTimeout = 10000;
	        } catch (Exception e) {
	            //e.printStackTrace();
	            log.error(e, e);
	        } finally {
	            HttpConnectionManagerParams params = connectionManager.getParams();
	            params.setConnectionTimeout(connectionTimeout);
	            params.setSoTimeout(soTimeout);
	            params.setMaxTotalConnections(maxThreadsTotal);
	            if (maxThreadsTotal > maxThreadsPerHost) {
	                params.setDefaultMaxConnectionsPerHost(maxThreadsPerHost);
	            } else {
	                params.setDefaultMaxConnectionsPerHost(maxThreadsTotal);
	            }
	            HostConfiguration hostConf = client.getHostConfiguration();
	            ArrayList<Header> headers = new ArrayList<Header>();
	            headers.add(new Header("Accept-Language",
	                    "en-us,zh-cn,zh-tw,en-gb,en;q=0.7,*;q=0.3"));
	            headers.add(new Header("Accept-Charset",
	                    "big5,gb2312,gbk,utf-8,ISO-8859-1;q=0.7,*;q=0.7"));
	            // headers.add(new Header(
	            // "Accept",
	            // "text/html,application/xml;q=0.9,application/xhtml+xml,text/xml;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"));
	            headers.add(new Header("Accept-Encoding", "x-gzip,   gzip"));
	            headers.add(new Header("Connection", "close"));
	            hostConf.getParams().setParameter("http.default-headers", headers);
	            initConnectionManagers();
	            initClients();
	        }
	    }

	    @SuppressWarnings("unused")
		private class UTF8PostMethod extends PostMethod {
	        public UTF8PostMethod(String url) {
	            super(url);
	        }

	        @Override
	        public String getRequestCharSet() {
	            // return super.getRequestCharSet();
	            return "utf-8";
	        }
	    }

	    private void initConnectionManagers() {
	        if (connectionManagers == null) {
	            connectionManagers = new MultiThreadedHttpConnectionManager[size];
	            for (int i = 0; i < size; i++) {
	                connectionManagers[i] = new MultiThreadedHttpConnectionManager();
	                HttpConnectionManagerParams params = connectionManagers[i]
	                        .getParams();
	                params.setConnectionTimeout((i + 1) * 1000);
	                params.setSoTimeout((i + 1) * 1000);
	                params.setMaxTotalConnections(maxThreadsTotal / size * 2);
	                params.setDefaultMaxConnectionsPerHost(maxThreadsPerHost / size
	                        * 2);
	            }

	        }
	    }

	    private void initClients() {
	        if (clients == null) {
	            clients = new HttpClient[size];
	            for (int i = 0; i < size; i++) {
	                clients[i] = new HttpClient(connectionManagers[i]);
	            }
	        }
	    }

	    public String sendRequest( String url, int timeout)
	    {
	    	configureClient();
	    	
	        if (timeout > size - 1 || timeout < 1) {
	            return null;
	        }
	        PostMethod post = new PostMethod(url);
	        InputStream in = null;
	        BufferedReader reader = null;
	        String retStr = null;
	        try {
				log.info("请求地址："+url);
		        post.setRequestHeader("Content-type", "text/xml; charset=utf-8");
		        post.setRequestHeader("Content-length", "0");
		        post.setRequestHeader("connection", "close");
		        int reCode = 0;
	            reCode = clients[timeout - 1].executeMethod(post);
	            if (reCode == HttpStatus.SC_OK) {
	                in = post.getResponseBodyAsStream();
	                if (in != null) {
	                    reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
	                    if (reader != null) {
	                        String line = null;
	                        StringBuffer sb = new StringBuffer();
	                        while ((line = reader.readLine()) != null) {
	                            sb.append("\n"+line);
	                        }
	                        retStr = sb.toString();
	                    }
	                }
	            }
	        }catch (Exception e){
	        	retStr = null;
	        	System.out.println(e);
	        }finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	                if (reader != null) {
	                    reader.close();
	                }
	            } catch (Exception e) {
	                log.error(e, e);
	            } finally {
	                post.releaseConnection();
	            }
	        }
	        return retStr;
	    }

	    public static void main(String[] args) throws UnsupportedEncodingException
	    {
	    	HttpProxy httpProxy = new HttpProxy();
	    	String jsondata = Base64Ext.encode("{'jsondata':[{'EMPID':'112233','MAJOR':null}]}".getBytes());
	    	String url = "http://localhost:8080/ydfdm/actions/sendIncData.action?sysCode=SOA&domainId=YD_EMPS&jsondata=";
	    	String ret = httpProxy.sendRequest(url, 20);
	    	System.out.println(JSON.parse(ret));
	    	
	    }
}
